﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using RoketSolutions.SP2010.Infrostructure.UI.Controls.Interfaces;
using RoketSolutions.SP2010.Infrostructure.UI.WebParts;
using RoketSolutions.SP2010.Infrostructure.Common.Extensions;

namespace RoketSolutions.SP2010.Infrostructure.ControlTemplates.RoketSolutions.SP2010.Infrostructure
{
    public partial class LocalizationToolPartControl : UserControl, IToolPartControl<LocalizationSettings>
    {
        #region / Properties /

        public Control Control
        {
            get { return this; }
        }

        private LocalizationSettings _currentSettings;
        private LocalizationSettings CurrentSettings
        {
            get { return _currentSettings ?? (_currentSettings = ViewState["CurrentSettings"] as LocalizationSettings); }
            set { ViewState["CurrentSettings"] = _currentSettings = value; }
        }

        private bool IsInitPhase { get; set; }

        #endregion

        #region / Controls Event Handlers /

        protected override void OnLoad(EventArgs e)
        {
            if (IsInitPhase)
            {
                BindData();
            }
        }

        #endregion

        #region / Methods /

        public void Initialize(LocalizationSettings settings)
        {
            if (CurrentSettings == null)
            {
                CurrentSettings = settings;
                IsInitPhase = true;
            }
        }

        public LocalizationSettings SaveData()
        {
            if (CurrentSettings != null)
            {
                UpdateConfig(CurrentSettings);
                return CurrentSettings;
            }
            return null;
        }

        private void BindData()
        {
            CheckBoxAutoDetect.Checked = CurrentSettings.UseAutoDetectMode;

            DropDownLanguages.Items.Clear();
            foreach (var supportedLang in CurrentSettings.SupportedLanguages)
            {
                var langName = supportedLang.ToLower();
                DropDownLanguages.Items.Add(new ListItem(langName, langName));
            }
            if (!CurrentSettings.SelectedLanuguage.IsNullOrEmpty())
            {
                DropDownLanguages.SelectedValue = CurrentSettings.SelectedLanuguage;
            }
            else if (CurrentSettings.SupportedLanguages.Contains("en-us", true))
            {
                DropDownLanguages.SelectedValue = "en-us";
            }
        }

        private void UpdateConfig(LocalizationSettings settings)
        {
            settings.UseAutoDetectMode = CheckBoxAutoDetect.Checked;
            settings.SelectedLanuguage = DropDownLanguages.SelectedValue;
        }

        #endregion

    }
}
